let app = getApp();
const extConfig = app.siteInfo;
const isCompanyCloudTemplate = Number(extConfig.isCloudTemplate) === 1 ? true : false;

Page({
  data: {
    isWebview: false,
    is_tabbar: app.siteInfo.tabbar_type === '2',
  },

  navigateToModulePage(pagePath, params) {
    if (isCompanyCloudTemplate) {
      app.util.request({
        url: 'entry/wxapp/api',
        data: { type: 16 },
        module: 'ws_micro_company',
        success: (res) => {
          if (res.data && res.data.data) {
            const templateOrder = Number(res.data.data.template_order);
            pagePath = pagePath.replace(/ws_micro_company/i, `ws_micro_company_${templateOrder === 0 ? 'visual' : templateOrder}`);
            app.util.navigateTo(pagePath, params || '', false);
          }
        },
        fail: (res) => {
          console.log(`get template order fail`, res);
        },
      });
    } else {
      app.util.navigateTo(pagePath, params || '', false);
    }
  },

  toArticle: function(e) {
    // 热区组件跳转事件
    let { pageType, pagePath } = e.detail.href;
    const module = app.siteInfo.module;
    if ((pageType === '1' || pageType === '4') && pagePath) {
      // 普通跳转或带参数跳转
      if (module === 'ws_micro_shop') {
        // 兼容微商城后台配置的轮播、导航页面路径
        if (/^\/pages/.test(pagePath)) {
          if (pagePath.indexOf('/book/') > 0) {
            pagePath = `ws_micro_shop_book${pagePath}`;
          } else if (pagePath.indexOf('/pt/') > 0) {
            pagePath = `ws_micro_shop_pt${pagePath}`;
          } else if (pagePath.indexOf('/miaosha/') > 0) {
            pagePath = `ws_micro_shop_ms${pagePath}`;
          } else {
            pagePath = `ws_micro_shop${pagePath}`;
          }
        }
        if (/^\/pages\/list\/list/.test(pagePath)) {
          pagePath = `${pagePath}&integral=0`;
        }
      }
      this.navigateToModulePage(pagePath);
    }
    if (pageType === '3' && pagePath) {
      // web-view跳转
      this.navigateToModulePage(`/${module}/pages/web/web`, { url: pagePath, webview_url: pagePath });
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    // 单个独立插件直接跳转到插件首页
    if (app.siteInfo.module === 'ws_empty') {
      app.util.request({
        url: 'auth/session/current_builtin',
        success: (res) => {
          if (res.data && res.data.errno === 0) {
            const moduleList = app.siteInfo.appJson || [];
            const plugin = res.data.data && res.data.data.plugin;
            switch (plugin) {
              case 'cm_poster':
                app.util.navigateTo('/ws_empty/pages/poster', {}, true);
                break;
              case 'cm_friend_help':
                app.util.navigateTo('/common/page/friend_help/friend_help', { curModule: 'ws_empty' }, true);
                break;
              case 'cm_cards_collecting':
              case 'cm_lottery':
                app.util.request({
                  url: plugin === 'cm_cards_collecting' ? 'wxapp/home/cards_collecting' : 'wxapp/home/lottery',
                  success: (res) => {
                    if (res.data && res.data.errno === 0) {
                      const data = res.data.data;
                      if (data) {
                        const activity = data[0] || {};
                        if (plugin === 'cm_lottery' && !activity.lottory_type) {
                          return wx.showModal({
                            title: '提示',
                            content: '暂时没有抽奖活动',
                            showCancel: false,
                            success: function (res) {
                            },
                          });
                        }
                        const path =
                            plugin === 'cm_cards_collecting'
                              ? `/cm_cards_collecting/pages/index/index?id=${activity.id}`
                              : `/cm_lottery/pages/index/index?type=${activity.lottory_type}&id=${activity.id}`;
                        app.util.navigateTo(path, {}, true);
                      }
                    }
                  },
                });
                break;

              default:
                if (moduleList.length === 2) {
                  app.util.navigateTo(moduleList[1].homePage, {}, true);
                  return;
                } else {
                  this.loadCustomData();
                }
                break;
            }
          }
        },
      });
    } else {
      this.loadCustomData();
    }
    this.getCustomPageTitle();
  },

  onShareAppMessage: function () {
  },

  loadCustomData() {
    app.utils.getCustomDataByType('customComponent').then((res) => {
      // 排序
      res.customComponent.sort((item1, item2) => Number(item1.no) - Number(item2.no));
      if (res.customComponent.length > 0) {
        res.customComponent.map((e) => {
          let value = {};
          try {
            e.configObj = JSON.parse(e.config);
            value = e.configObj;
          } catch (err) {
            console.warn(err);
          }

          e.isShow = value.isShow;
          if (e.moduleComID === '101') {
            // image-cube
            if (value.model && value.model.images) {
              // TODO魔方数据逻辑
            }
          }
          if (e.moduleComID === '102') {
            // hot-zone
            if (value && value.model && value.model.hotAreas) {
              let areas = value.model.hotAreas;
              areas.map((areaItem) => {
                areaItem.link.coords = areaItem.link.startCords.concat(areaItem.link.endCords);
                return areaItem;
              });
            }
          }
          if (e.moduleComID === '103') {
            // rich-text
          }
          if (e.moduleComID === '104') {
            // vedio-com
          }
          return e;
        });
      }

      this.setData({
        customComponent: res.customComponent,
      });
      console.log('res.customComponent', res.customComponent);
    });
  },

  getCustomPageTitle() {
    app.utils.getCustomPageTitle().then(res => {
      if (res.code === 1) {
        wx.setNavigationBarTitle({
          title: res.result || '微页面',
        });
      }
    });
  },
});
